package br.com.catalogodigital.dao;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.servlet.http.HttpSession;

import org.primefaces.model.UploadedFile;

import br.com.catalogodigital.entity.Anunciante;
import br.com.catalogodigital.entity.Anuncio;
import br.com.catalogodigital.entity.Servico;
import br.com.catalogodigital.factory.Factory_Generic;

public class ServicoDao {

	EntityManager manager;

	public ServicoDao() {
		Factory_Generic factory = new Factory_Generic();
		manager = factory.manager();
	}

	// / METODOS DAO G ENERICOS
	public void inserir(Servico servico) {
		manager.getTransaction().begin();
		manager.persist(servico);
		manager.getTransaction().commit();
		manager.close();
	}
	
	public Servico buscarId(int id) {
		manager.getTransaction().begin();
		Servico resultado = manager.find(Servico.class, id);
		manager.close();
		return resultado;
	}


	// ALTERAR ANUNCIO
	public void alterar(Servico servico) {
		
		FacesContext fc = FacesContext.getCurrentInstance();
		ExternalContext ec = fc.getExternalContext();
		HttpSession session = (HttpSession) ec.getSession(false);

		servico.getAnunciante().setId(
				(Integer) session.getAttribute("idAnunciante"));


		manager.getTransaction().begin();
		manager.merge(servico);
		manager.getTransaction().commit();
		manager.close();
	}

	
	public List<Servico> listar(){
		
		FacesContext fc = FacesContext.getCurrentInstance();
		ExternalContext ec = fc.getExternalContext();
		HttpSession session = (HttpSession) ec.getSession(false);

		int id = (Integer) session.getAttribute("idAnunciante");

		manager.getTransaction().begin();
		Query consulta = manager
				.createQuery("SELECT x from Servico as x WHERE x.anunciante.id ="
						+ id);
		manager.close();
		return consulta.getResultList();
		
	}
	
	
	// DELETAR ANUNCIO
	public void deletar(int l) {
		
	}



	public EntityManager getManager() {
		return manager;
	}

	public void setManager(EntityManager manager) {
		this.manager = manager;
	}

}
